package com.own.component.util.position;

import com.own.component.util.position.model.Ip2RegionModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * Ip2RegionUtil
 *
 * @author chenxueli
 * @date 2022-09-21 17:03:00
 */
@Slf4j
public class Ip2RegionUtil {

    private static final byte[] V_INDEX;
    private static final String DB_PATH;

    /**
     * 默认的归属地信息
     */
    private static final Ip2RegionModel DEFAULT_REGION = new Ip2RegionModel("", "未知|0|未知|未知|未知");

    static {
        // 获取文件路径信息
        var resource = new ClassPathResource("data/ip2region.xdb");
        // 获取文件地址
        try {
            DB_PATH = resource.getURL().getPath();
        } catch (IOException e) {
            throw new RuntimeException("ip归属地数据库文件不存在");
        }
        // 获取索引信息
        try {
            V_INDEX = Searcher.loadVectorIndexFromFile(DB_PATH);
        } catch (Exception e) {
            throw new RuntimeException("ip归属地数据库文件索引加载失败");
        }
    }

    /**
     * 根据ip获取地理位置
     *
     * @param ip ip地址
     * @return 地理位置
     */
    public static Ip2RegionModel getRegion(String ip) {
        if (StringUtils.isBlank(ip)) {
            return DEFAULT_REGION;
        }
        // 使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithVectorIndex(DB_PATH, V_INDEX);
            var region = searcher.search(ip);
            return new Ip2RegionModel(ip, region);
        } catch (Exception e) {
            return DEFAULT_REGION;
        } finally {
            if (searcher != null) {
                try {
                    searcher.close();
                } catch (IOException ignored) {

                }
            }

        }
    }

}
